package edu.xmut.prototype.deepclone;

import java.io.*;

/**
 * @author 朔风
 * @date 2024-02-18 18:10
 */
public class DeepProtoType implements Serializable, Cloneable {
    private String name;

    private DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType(String name) {
        this.name = name;
    }


    @Override
    public DeepProtoType clone() {
        try {
            // 方式一：
            DeepProtoType clone = (DeepProtoType) super.clone();
            clone.setDeepCloneableTarget(clone.getDeepCloneableTarget().clone());
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    public DeepProtoType deepClone() {

        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            // 将当前对象以对象溜的方式输出
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObject = (DeepProtoType) ois.readObject();
            return copyObject;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        } finally {
            try {
                bos.close();
                bis.close();
                ois.close();
                oos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }

    @Override
    public String toString() {
        return "DeepProtoType{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }
}
